import {useState, useEffect, useRef} from 'react';
import {useNavigate,useSearchParams} from 'react-router-dom';
import PageTable from '@/components/PageTable.tsx';
import {findDicNameForDicCode} from '@/utils/dicAll.ts'
import DynamicSearchForm from '@/components/DynamicSearchForm/index.tsx'
import {
    companyCodeQueryOrgList,
    csvCarExport,
    exportProduct,
    queryAllCompany,
    queryIdByProcessId
} from "@/axios/apis.ts"
import ForceUpdate from '@/hook/forceUpdate.tsx'
import dayjs from 'dayjs';
import PageActionBar from "@/components/PageActionBar.tsx"
import {PlusOutlined} from "@ant-design/icons";
import {downloadFile} from "@/utils";

const CarInsuranceList = () => {
    const navigate = useNavigate()
    const [searchParams]= useSearchParams()
    // 强制更新
    const [searchFields, setSearchFields] = useState({
        search: [],
        expand: []
    })
    const [searchForm, setSearchForm] = useState({});
    const tableRef = useRef(null);
    const formRef = useRef(null);
    const {forceUpdate} = ForceUpdate();
    const companyCodeChange = async (value: string) => {
        formRef.current.updateFormData({key:'companyOrgCode',val: undefined})
        fields.search[1].disabled = !value
        if (value) {
            const res = await companyCodeQueryOrgList({companyCode: value})
            if (+res.code === 200) {
                fields.search[1].options = res.data
            }
        }
        setSearchFields(fields)
        forceUpdate()
    }
    const fields = {
        search: [
            {
                type: 'select',
                name: 'companyCode',
                label: '保险公司',
                placeholder: '请选择',
                options: [],
                fieldNames: {
                    label: 'name',
                    value: 'companyCode'
                },
                onChange: companyCodeChange
            },
            {
                type: 'cascader',
                name: 'companyOrgCode',
                label: '保险公司分支机构',
                placeholder: '请选择',
                options: [],
                fieldNames: {
                    label: 'orgName', value: 'orgCode', children: 'childOrgMap'
                },
                disabled: true
            },
            {
                type: 'input',
                name: 'batchCode',
                label: '批次号',
                placeholder: '请输入',
            },
        ],
        expand: [
            {
                type: 'input',
                name: 'policyNo',
                label: '保单号',
                placeholder: '请输入',
            },
            {
                type: 'rangePicker',
                name: 'createTime',
                label: '录入日期'
            },
            // {
            //     type: 'custom',
            //     name: 'customField',
            //     label: '自定义字段',
            //     render: () => <Input placeholder="自定义渲染" />
            // }
        ]
    }
    const columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            render: (_1, _2, index) => <>{index + 1}</>,
            width: 50
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <div className="table-options">
                    <span className="operation_style" onClick={()=>{
                        let params = new URLSearchParams()
                        params.append('orderId',record.orderId)
                        params.append('type','details')
                        navigate(`/CarInsuranceDetails?${params.toString()}`)
                    }}>明细</span>
                </div>
            ),
            width: 100
        },
        {
            title: "机构名称",
            dataIndex: "orgName",
            key: "orgName",
        },
        {
            title: "投保人名称",
            dataIndex: "insurerName",
            key: "insurerName",
            width: 100
        },
        {
            title: "批次号",
            dataIndex: "batchCode",
            key: "batchCode",
            width: 100
        }, {
            title: "保单号",
            dataIndex: "orderId",
            key: "orderId",
        }, {
            title: "车牌号",
            dataIndex: "licenseno",
            key: "licenseno",
            width: 100
        }, {
            title: "项目名称",
            dataIndex: "projectName",
            key: "projectName",
        }, {
            title: "险种名称",
            dataIndex: "mainRiskName",
            key: "mainRiskName",
            width: 100
        }, {
            title: "生效日期",
            dataIndex: "valiDate",
            key: "valiDate",
        }, {
            title: "录入日期",
            dataIndex: "createTime",
            key: "createTime",
        }, {
            title: "保单状态",
            dataIndex: "policyStatus",
            key: "policyStatus",
            render: (value) => <>{findDicNameForDicCode('APPROVAL.STATUS', value.slice(1))}</>,
            width: 100
        }, {
            title: "发起人",
            dataIndex: "createUserName",
            key: "createUserName",
            width: 80
        }, {
            title: "经纪人姓名",
            dataIndex: "saleName",
            key: "saleName",
            width: 100
        }
    ];
    const handleSearch = (values: any) => {
        if (values.createTime?.length) {
            values.createStartTime = dayjs(values.createTime[0]).startOf('date').format('YYYY-MM-DD HH:mm:ss')
            values.createEndTime = dayjs(values.createTime[1]).endOf('date').format('YYYY-MM-DD HH:mm:ss')
            delete values.createTime
        }
        if (values.companyOrgCode?.length) {
            values.companyOrgCode = values.companyOrgCode[values.companyOrgCode.length - 1]
        }
        setSearchForm(values)
        tableRef.current.fetchData({}, values)
    }
    const btnList = [
        {
            name: '新增',
            type: 'primary',
            icon: <PlusOutlined />,
            onClick: () => {
                queryIdByProcessId({
                    processId: '202404171013'
                }).then(res => {
                    if (+res.code === 200) {
                        const params = new URLSearchParams()
                        params.append('processId', res.data.id)
                        params.append('processName', res.data.processName)
                        navigate(`/OAExamine/Application?${params.toString()}`)
                    }
                })
            }
        },
        {
            name: '批量导出',
            onClick: () => {
                let data = formRef?.current?.getFormData()
                setSearchForm(data)
                csvCarExport(data).then(res => {
                    downloadFile(res,'车险.csv')
                    // try {
                    //     if (res.data.code === 300) {
                    //         MessageBox.alert(res.data.msg, '提示', {
                    //             confirmButtonText: '确定',
                    //         })
                    //     }
                    // } catch (e) {
                    //     let blob = new Blob([res], {type: "application/vnd.ms-excel"}),// 此处为生成doc
                    //         link = document.createElement("a"),
                    //         href = window.URL.createObjectURL(blob);
                    //     link.href = href;
                    //     link.download = '车险' + '.csv';
                    //     document.body.appendChild(link);
                    //     link.click();
                    //     document.body.removeChild(link);
                    //     window.URL.revokeObjectURL(href);
                    // }

                })
            }
        },
    ]

    useEffect(() => {
        queryAllCompany().then(res => {
            if (+res.code === 200) {
                fields.search[0].options = res.data
                setSearchFields(fields)
            }
        })
    }, [])
    return (
        <>
            <DynamicSearchForm fields={searchFields} onSearch={handleSearch} ref={formRef}/>
            <PageActionBar btnList={btnList} />
            <PageTable
                columns={columns}
                reqestUrl="CarInformation"
                searchForm={searchForm}
                ref={tableRef}
            />
        </>
    );
};

export default CarInsuranceList;